package com.edev.support.utils;

import com.edev.support.exception.OrmException;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

/**
 * The utilities for the spring application context
 */
@Component
public class SpringHelper {
    @Autowired
    private ApplicationContext applicationContext;

    /**
     * 根据Bean名称从Spring上下文中获取Bean实例
     * <p>
     * 使用示例：
     * <pre>
     * Object service = springHelper.getService("userService");
     * </pre>
     * 实现说明：
     * 1. 优先检查beanName有效性
     * 2. 通过applicationContext.getBean()获取实例
     * 3. 捕获并转换Spring原生异常为OrmException
     * @param beanName Bean的名称（需与Spring容器中注册的名称一致）
     * @return 查找到的Bean实例
     * @throws OrmException 出现以下情况时抛出：
     *                      - bean名称为空
     *                      - 找不到对应的Bean定义
     *                      - 获取Bean过程中发生异常
     */
    public Object getService(String beanName) {
        if (beanName == null || beanName.isEmpty())
            throw new OrmException("The bean name is empty!");
        try {
            return applicationContext.getBean(beanName);
        } catch (NoSuchBeanDefinitionException e) {
            throw new OrmException("No such bean definition in the spring context!", e);
        } catch (BeansException e) {
            throw new OrmException("error when get the bean[%s]", e, beanName);
        }
    }
}
